from flask import Blueprint, render_template, request, flash, redirect, url_for
from models import db, HierarchyConfig
from utils.form_utils import HierarchyForm
from utils.export_utils import export_to_excel


hierarchy_bp = Blueprint('hierarchy', __name__, url_prefix='/hierarchy')

@hierarchy_bp.route('/')
def index():
    hierarchies = HierarchyConfig.query.order_by(HierarchyConfig.level).all()
    return render_template('hierarchy/index.html', hierarchies=hierarchies)

@hierarchy_bp.route('/create', methods=['GET', 'POST'])
def create():
    form = HierarchyForm()
    form.parent_id.choices = [('', '无父节点')] + [
        (h.node_id, f"{h.code} - {h.name}") 
        for h in HierarchyConfig.query.all()
    ]
    
    if form.validate_on_submit():
        new_node = HierarchyConfig(
            node_id=form.node_id.data,
            parent_id=form.parent_id.data or None,
            level=form.level.data,
            code=form.code.data,
            name=form.name.data,
            version=form.version.data
        )
        db.session.add(new_node)
        db.session.commit()
        flash('业务层级创建成功', 'success')
        return redirect(url_for('hierarchy.index'))
    
    return render_template('hierarchy/create.html', form=form)

@hierarchy_bp.route('/edit/<node_id>', methods=['GET', 'POST'])
def edit(node_id):
    node = HierarchyConfig.query.get_or_404(node_id)
    form = HierarchyForm(obj=node)
    
    # 排除当前节点及其子节点作为父节点
    exclude_ids = [n.node_id for n in node.children] + [node_id]
    form.parent_id.choices = [('', '无父节点')] + [
        (h.node_id, f"{h.code} - {h.name}") 
        for h in HierarchyConfig.query.filter(HierarchyConfig.node_id.notin_(exclude_ids)).all()
    ]
    
    if form.validate_on_submit():
        node.parent_id = form.parent_id.data or None
        node.level = form.level.data
        node.code = form.code.data
        node.name = form.name.data
        node.version = form.version.data
        db.session.commit()
        flash('业务层级更新成功', 'success')
        return redirect(url_for('hierarchy.index'))
    
    return render_template('hierarchy/edit.html', form=form, node=node)

@hierarchy_bp.route('/tree')
def tree_view():
    # 递归构建层级树
    def build_tree(parent_id=None):
        nodes = HierarchyConfig.query.filter_by(parent_id=parent_id).all()
        return [{
            'id': node.node_id,
            'text': f"{node.code} - {node.name}",
            'children': build_tree(node.node_id)
        } for node in nodes]
    
    tree_data = build_tree()
    return render_template('hierarchy/tree.html', tree_data=tree_data)
@hierarchy_bp.route('/export', methods=['GET'])
def export_hierarchy():
    # 获取所有业务层级
    hierarchies = HierarchyConfig.query.all()
    
    # 转换为字典列表
    hierarchy_list = []
    for node in hierarchies:
        hierarchy_list.append({
            "node_id": node.node_id,
            "parent_id": node.parent_id,
            "level": node.level,
            "code": node.code,
            "name": node.name,
            "is_active": "启用" if node.is_active else "停用",
            "version": node.version
        })
    
    # 列名映射
    columns_mapping = {
        "node_id": "节点ID",
        "parent_id": "父节点ID",
        "level": "层级",
        "code": "编码",
        "name": "名称",
        "is_active": "状态",
        "version": "版本"
    }
    
    return export_to_excel(hierarchy_list, "业务层级", columns_mapping)

@hierarchy_bp.route('/delete/<node_id>', methods=['POST'])
def delete(node_id):
    node = HierarchyConfig.query.get_or_404(node_id)
    
    # 检查是否有子节点
    if node.children:
        flash('无法删除有子节点的层级', 'danger')
        return redirect(url_for('hierarchy.index'))
    
    db.session.delete(node)
    db.session.commit()
    flash('业务层级删除成功', 'success')
    return redirect(url_for('hierarchy.index'))